package me.exchange.com.modules.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.exchange.com.aop.log.Log;
import me.exchange.com.exception.BadRequestException;
import me.exchange.com.modules.system.domain.Menu;
import me.exchange.com.modules.system.domain.RolesMenus;
import me.exchange.com.modules.system.dto.MenuDto;
import me.exchange.com.modules.system.dto.MenuQueryCriteria;
import me.exchange.com.modules.system.dto.UserDto;
import me.exchange.com.modules.system.service.MenuService;
import me.exchange.com.modules.system.service.RoleService;
import me.exchange.com.modules.system.service.RolesMenusService;
import me.exchange.com.modules.system.service.UserService;
import me.exchange.com.utils.Result;
import me.exchange.com.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Zheng Jie
 * @date 2018-12-03
 */
@Api(tags = "系统：菜单管理")
@RestController
@RequestMapping("/api/menus")
@SuppressWarnings("unchecked")
public class MenuController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolesMenusService rolesMenusService;

    private static final String ENTITY_NAME = "sys_menu";

    @Log("导出菜单数据")
    @ApiOperation("导出菜单数据")
    @PostMapping(value = "/list/download")
    @PreAuthorize("@el.check('menu:list')")
    public void download(HttpServletResponse response, MenuQueryCriteria criteria) throws IOException {
        List<MenuDto> menus= menuService.queryAll(criteria);
        menuService.download(menus,response);
    }

    @ApiOperation("获取前端所需菜单")
    @PostMapping(value = "/build")
    public ResponseEntity<Object> buildMenus(){
        UserDto user = userService.findByName(SecurityUtils.getUsername());
        List<MenuDto> menuDtoList = menuService.findByRoles(roleService.findByUsersId(user.getId()));
        List<MenuDto> menuDtos = (List<MenuDto>) menuService.buildTree(menuDtoList).get("content");
        Object menu =  menuService.buildMenus(menuDtos);
        return new ResponseEntity<>(Result.ok("前端所需菜单获取成功").put("menu",menu),HttpStatus.OK);
    }

    @ApiOperation("返回全部的菜单")
    @PostMapping(value = "/tree")
    @PreAuthorize("@el.check('menu:list','roles:list')")
    public ResponseEntity<Object> getMenuTree(){
        Object menu =menuService.getMenuTree(menuService.findByPid(0L));
        return new ResponseEntity<>(Result.ok("全部的菜单返回成功").put("menu",menu),HttpStatus.OK);
    }

    @Log("查询菜单")
    @ApiOperation("查询菜单")
    @PostMapping("/list")
    @PreAuthorize("@el.check('menu:list')")
    public ResponseEntity<Object> getMenus(MenuQueryCriteria criteria, Pageable pageable){
        if(criteria.getCAdminTime() != null && criteria.getCAdminTime().size()>0){
            if(criteria.getCAdminTime().get(1).before(criteria.getCAdminTime().get(0))){
                return new ResponseEntity<>(Result.error("操作失败，查询时间段设置不正确"),HttpStatus.OK);
            }
        }
        List<MenuDto> menuDtoList = menuService.queryAll(criteria);
        //Map<String,Object> menuMap = menuService.buildTree(menuDtoList);
        return new ResponseEntity<>(Result.ok("查询菜单成功").put("menuList",menuDtoList),HttpStatus.OK);
    }

    @PostMapping("/queryInfo")
    @Log("查询菜单详情")
    @ApiOperation("查询菜单详情")
    @PreAuthorize("@el.check('dict:list')")
    public ResponseEntity<Object> queryInfo(Long id){
        MenuDto menuDto =  menuService.findById(id);
        return new ResponseEntity<>(Result.ok("菜单详情查询成功").put("menu",menuDto),HttpStatus.OK);
    }

    @Log(value="新增菜单",code="system_menu")
    @ApiOperation("新增菜单")
    @PostMapping("/add")
    @PreAuthorize("@el.check('menu:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Menu resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        MenuDto menuDto = menuService.create(resources);

        RolesMenus rolesMenus = new RolesMenus();
        rolesMenus.setRoleId(1L);
        rolesMenus.setMenuId(menuDto.getId());

        rolesMenusService.create(rolesMenus);
        return new ResponseEntity<>(Result.ok("菜单创建成功"),HttpStatus.OK);
    }

    @Log(value="修改菜单",code="system_menu")
    @ApiOperation("修改菜单")
    @PostMapping("/update")
    @PreAuthorize("@el.check('menu:edit')")
    public ResponseEntity<Object> update(@Validated(Menu.Update.class) @RequestBody Menu resources){
        menuService.update(resources);
        return new ResponseEntity<>(Result.ok("菜单修改成功"),HttpStatus.OK);
    }
    @Log(value="菜单状态修改",code="system_menu")
    @ApiOperation("菜单状态修改")
    @PostMapping("/updateStatus")
    @PreAuthorize("@el.check('dept:edit')")
    public ResponseEntity<Object> updateStatus(@RequestBody MenuQueryCriteria criteria){
        menuService.updateStatus(criteria);
        return new ResponseEntity<>(Result.ok("状态修改成功"),HttpStatus.OK);
    }
    @Log(value="删除菜单",code="system_menu")
    @ApiOperation("删除菜单")
    @PostMapping("/del")
    @PreAuthorize("@el.check('menu:del')")
    public ResponseEntity<Object> delete(@RequestBody MenuQueryCriteria criteria){
        Set<Menu> menuSet = new HashSet<>();
        for (Long id : criteria.getIds()) {
            List<Menu> menuList = menuService.findByPid(id);
            menuSet.add(menuService.findOne(id));
            menuSet = menuService.getDeleteMenus(menuList, menuSet);
        }
        menuService.delete(menuSet);
        return new ResponseEntity<>(Result.ok("菜单删除成功"),HttpStatus.OK);
    }
}
